package zhou.servlet;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import jman.service.UserService;
import jman.service.VoteService;

/**
 * Servlet implementation class Login
 */
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Login() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		int id=0;
		String sId=request.getParameter("id");
		if(sId!=""){
			id=Integer.valueOf(sId);
		}
		String pwd=(String) request.getParameter("pwd");
		String role="";
		HttpSession session=request.getSession();
		boolean flag=false;
		UserService us=new UserService();
		try {
			flag=us.login(id, pwd);
			role=us.getRole(id);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(flag){
			session.setAttribute("id", id);
			if("学生".equals(role)){
				VoteService vd=new VoteService();
				try {
					session.setAttribute("voteList",vd.getListForStudent(id));
					session.setAttribute("voteList1",vd.getListForStudentToVote(id));
					session.setAttribute("number",vd.getListForStudentToVote(id).size());
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				request.getRequestDispatcher("/jman/admin/stadmin.jsp").forward(request, response);
			}else if("老师".equals(role)){
				VoteService vd=new VoteService();
				try {
					session.setAttribute("voteList", vd.getListForTeacher(id));
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				request.getRequestDispatcher("/jman/admin/thadmin.jsp").forward(request, response);
			}
		}else{
			request.getRequestDispatcher("/jman/admin/loginfail.html").forward(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
